﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Privosoft.DataFrame.UI
{
    public partial class ImportDataControl : UserControl
    {
        private IList<SchemaInfo> _schemas;
        public ImportDataControl()
        {
            InitializeComponent();
            
            cbSchema.SelectedValueChanged += new EventHandler(cbSchema_SelectedValueChanged);
            // load schema info
            InitSchemaInfo();
        }

        void cbSchema_SelectedValueChanged(object sender, EventArgs e)
        {
            // bind columns to dg
            var sc = GetSelectedSchema();
            if (sc != null)                
                dgvSchema.DataSource = sc.Columns;             
        }

        private SchemaInfo GetSelectedSchema()
        {
            var selectedSchema = cbSchema.SelectedValue as string;
            if (string.IsNullOrEmpty(selectedSchema) == false)
                return _schemas.FirstOrDefault(s => s.Name == selectedSchema);
            return null;
        }

        private void InitSchemaInfo()
        {
            using (var db = new DbContext(new SqlConnection(Properties.Settings.Default.DBConnectionString), Form1.DbSchema))
            {
                _schemas = db.GetSchemas(true).ToList();
                // bind schemas to the drop down
                cbSchema.DataSource = _schemas.ToList();
                cbSchema.ValueMember = "Name";
                cbSchema.DisplayMember = "Name";
            }
        }

        private void btnFileSelect_Click(object sender, EventArgs e)
        {
            var dlg = new OpenFileDialog();
            dlg.Title = "Select Data File";
            dlg.Filter = "CSV Commad Delim Files|*.csv";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                var f = dlg.FileName;
                txtFilePath.Text = f;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // load data
            var f = txtFilePath.Text;
            try
            {
                if (System.IO.File.Exists(f))
                {
                    var dt = FileReader.ReadFile(f, 200);
                    dgvData.DataSource = dt;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Data Preview: " + ex.Message, "Data Preview Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                using (new CursorKeeper(Cursors.WaitCursor))
                {
                    var sw = System.Diagnostics.Stopwatch.StartNew();
                    var sc = GetSelectedSchema();
                    if (sc == null) return;

                    var f = txtFilePath.Text;
                    if (System.IO.File.Exists(f) == false) return;

                    var cn = new SqlConnection(Properties.Settings.Default.DBConnectionString);
                    ImportStatsInfo stats = null;
                    using (var db = new DbContext(cn, Form1.DbSchema))
                        stats = FileReader.ImportCsv(f, sc, db);

                    sw.Stop();
                    lblImportTime.Text = "Took: " + sw.ElapsedMilliseconds / 1000 + " secs to import";

                    // bind errors if any
                    dgvImportErrors.DataSource = stats.Errors;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to import data: " + ex.Message, "Data Preview Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            }
        }
    }
}
